package com.common.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


@Controller
@RequestMapping(value = "/file")
public class FileDownloadController {
    private static Logger logger = Logger.getLogger(FileDownloadController.class);

    @RequestMapping("/download")
    public Object download(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("<-------------文件请求路径-------------->" + path);
        ServletOutputStream out = null;
        FileInputStream ips = null;
        String url=path;
        try {
            File file = new File(url);
            if (!file.exists()) {
                logger.info("<-------------文件不存在-------------->"+path);
                response.setStatus(response.SC_NOT_FOUND );
                return response;
            }
            long length = file.length();
            if (length > Integer.MAX_VALUE) {
                throw new RuntimeException("<-------文件太大------>");
            }
            ips = new FileInputStream(file);
            response.setContentType("octets/stream");
            response.addHeader("Content-Type", "text/html; charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "ISO8859-1"));
            out = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024*10];
            while ((len = ips.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            logger.info("<----------文件流处理异常---------->"+e.getMessage());
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR );
        } finally {
            out.close();
            ips.close();
        }
        return null;
    }

}
